package club.zhilin.guli.service.sms.controller;

import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import club.zhilin.guli.service.sms.service.ISmsService;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhilin
 * @since 2022/2/24 11:31
 */
@RefreshScope
@RestController
@RequestMapping("/portal/sms")
@Api(tags = "短信服务")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmsController {

    private final ISmsService iSmsService;

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @GetMapping("/send/{phone}")
    public CommonResult<String> random(@PathVariable String phone) {
        // 校验手机号
        if (StringUtils.isNotEmpty(phone) || PhoneUtil.isMobile(phone)) {
            // 生成验证码
            String random = RandomUtil.randomNumbers(6);
            iSmsService.send(phone, random);
            redisTemplate.opsForValue().set(phone, random, 5, TimeUnit.MINUTES);
            return CommonResult.success("短信发送成功");
        }
        return CommonResult.failed(CommonResultCodeEnum.LOGIN_PHONE_ERROR);
    }
}
